/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.codelab.slice;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.codelab.ResourceTable;
import com.huawei.codelab.beans.User;
import com.huawei.codelab.utils.*;
import com.huawei.codelab.provider.TabPageSliderProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.bundle.IBundleManager;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * MainAbilitySlice
 *
 * @since 2021-01-11
 */
public class MainAbilitySlice_max extends AbilitySlice {
    Gson gson =new Gson();
    List<Integer> layoutFileIds =new ArrayList<>();
    TabList tabList;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        String token = DataBaseUtil.getvalue("token", this);
        super.setUIContent(ResourceTable.Layout_ability_main_1);
        if (token!=null){
             tabList =(TabList)findComponentById(ResourceTable.Id_tab_list);
            String[] tabListTags ={"游戏中心","成员管理","我的","宝宝社区"};
            for (int i = 0; i < tabListTags.length; i++) {
                TabList.Tab tab = tabList.new Tab(this);
                tab.setText(tabListTags[i]);
                tabList.addTab(tab);
            }



            //这里仅仅拿到界面展示，没有任何点击功能
            layoutFileIds.add(ResourceTable.Layout_ability_main);
            layoutFileIds.add(ResourceTable.Layout_ability_main_index);
            layoutFileIds.add(ResourceTable.Layout_ability_main_user_center);
            layoutFileIds.add(ResourceTable.Layout_ability_baby);
            PageSlider pageSlider =(PageSlider)findComponentById(ResourceTable.Id_page_slider);
            pageSlider.setProvider(new TabPageSliderProvider(layoutFileIds,this));


            tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
                @Override
                public void onSelected(TabList.Tab tab) {
                    //取索引
                    int index = tab.getPosition();

                    pageSlider.setCurrentPage(index);
                    //绑定首页事件
                    if(index==0){
                        initOne(pageSlider);
                    }
                    //绑定成员管理
                    else if(index==1){
                        initTwo(pageSlider);

                    }
                    //绑定我的
                    else if(index==2){
                        initThree(pageSlider);

                    }
                    //绑定宝宝摄取
                    else if(index==3){
                        initFour(pageSlider);
                    }
                    System.out.println("===========================index"+index);
                }
                @Override
                public void onUnselected(TabList.Tab tab) { }

                @Override
                public void onReselected(TabList.Tab tab) { }
            });
            pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
                @Override
                public void onPageSliding(int i, float v, int i1) {

                }
                @Override
                public void onPageSlideStateChanged(int i) { }

                @Override
                public void onPageChosen(int i) {
                    //i表示当前pageslider的索引
                    if(tabList.getSelectedTabIndex()!=i){
                        System.out.println("===========================滑动块"+i);

                        tabList.selectTabAt(i);
                    }
                }
            });

            tabList.selectTabAt(0);
        }else{
            //有两种选择，直接显示视图
//            setUIContent(ResourceTable.Layout_ability_login);
            //跳转视图，前提需要当前界面是视图
            present(new LoginAbilitySlice(),new Intent());
        }
    }






    //跳转井字游戏
//    public boolean isAppExist(Context context, String appPkg) {
//        try {
//            IBundleManager manager = context.getBundleManager();
//            return manager.isApplicationEnabled(appPkg);
//        } catch (IllegalArgumentException e) {
//            return false;
//        }
//    }
    //跳井字游戏
    public  void launchAppDetail(){
        Intent intent = new Intent();
        Set<String> entities = new HashSet<>();
        entities.add("android.intent.category.LAUNCHER");

        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("ohos.samples1.tictactoegame1")
                .withAbilityName("ohos.samples.tictactoegame.MainAbility")
                .withAction("android.intent.action.MAIN")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .withEntities(entities)
                .build();
        intent.setOperation(operation);
        startAbility(intent);
    }


    private void  initOne(PageSlider pageSlider){

        Component componentById = pageSlider.findComponentById(ResourceTable.Id_math_game);
        componentById.setClickedListener(component -> {
//            LogUtil.info(TAG, "Click ResourceTable Id_math_game");
            Intent mathGameIntent = new Intent();
            Operation operationMath = new Intent.OperationBuilder().withBundleName(getBundleName())
                    .withAbilityName(CommonData.ABILITY_MAIN)
                    .withAction(CommonData.MATH_PAGE)
                    .build();
            mathGameIntent.setOperation(operationMath);
            startAbility(mathGameIntent);

        });
        Component componentById2 = pageSlider.findComponentById(ResourceTable.Id_picture_game);
        componentById2.setClickedListener(component -> {
            Intent pictureGameIntent = new Intent();
            Operation operationPicture = new Intent.OperationBuilder().withBundleName(getBundleName())
                    .withAbilityName(CommonData.ABILITY_MAIN)
                    .withAction(CommonData.PICTURE_PAGE)
                    .build();
            pictureGameIntent.setOperation(operationPicture);
            startAbility(pictureGameIntent);
        });
        Component componentById3 = pageSlider.findComponentById(ResourceTable.Id_ycl_game);
        componentById3.setClickedListener(component -> {
            TaskDispatcher globalTaskDispatcher =this.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            globalTaskDispatcher.asyncDispatch(()->{
                launchAppDetail();

            });
        });
    }
    private void  initTwo(PageSlider pageSlider){
        String userFamily = DataBaseUtil.getvalue("userFamily", this);

        TableLayout productListTable = (TableLayout)findComponentById(ResourceTable.Id_index_product_list_table);
        productListTable.removeAllComponents();


        TaskDispatcher globalTaskDispatcher =this.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(()->{
            String urlString = "http://120.26.194.73:9001/user/family?userfmailyid="+userFamily;
            String result = HttpRequestUtil.sendGetRequest(this,urlString);
            System.out.println("请求到------------------》"+result);
            //转json
            String jsonStr = gson.toJson(result);
//            List<User> list =gson.fromJson(jsonStr,new TypeToken<List<User>>(){}.getType());


            ArrayList<User> list = new ArrayList<User>();
            Type type = new TypeToken<List<User>>() {}.getType();
            list=gson.fromJson(result, type);
            ArrayList<User> finalList = list;
            getUITaskDispatcher().asyncDispatch(()->{
                System.out.println("=========================================================================遍历一次家庭成员");
               //遍历当前用户家庭成员
               for (User user: finalList){
                   DirectionalLayout template = (DirectionalLayout) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_product_list_item_template, null, false);
                   Image image = (Image)template.findComponentById(ResourceTable.Id_user_image);
                   Text name =(Text) template.findComponentById(ResourceTable.Id_user_name);
                   Text age =(Text) template.findComponentById(ResourceTable.Id_user_age);
                   String userImgAddress = user.getUserImgAddress();
                   String imgUrl =ApiUtil.IMG_BASE_PATH+userImgAddress;

                   //载入图片
                   LoadImageUtil.loadImg(this,imgUrl,image);
                   name.setText(user.getUserCall());
                   String s = "年龄:"+user.getUserAge().toString();
                   age.setText(s);
                   //加入table中（这里做了数据渲染，需要做异步操作，外层for循环建立异步操作）
                   productListTable.addComponent(template);

                   template.setClickedListener(component -> {
                       Intent intent =new Intent();
                       intent.setParam("userImgAddress",user.getUserImgAddress());
                       intent.setParam("userCall",user.getUserCall());
                       intent.setParam("userName",user.getUserName());
                       intent.setParam("userAge",user.getUserAge());
                       intent.setParam("userId",user.getUserId());
//                       TaskDispatcher globalTaskDispatcher1 =this.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
//                       globalTaskDispatcher1.asyncDispatch(()->{
//                       });
                       tabList.removeAllComponents();
                       //尝试release替代removeall
                       productListTable.release();
                       //删除下选四按钮  以及  原先所有成员

//                       productListTable.removeAllComponents();
                       //含bug版跳转-》无法返回
                       this.present(new DetailAbilitySlice(),intent);

//                       Intent mathGameIntent = new Intent();
//                       Operation operationMath = new Intent.OperationBuilder().withBundleName(getBundleName())
//                               .withAbilityName(CommonData.ABILITY_MAIN)
//                               .withAction(CommonData.DETAIL_PAGE)
//                               .build();
//                       mathGameIntent.setOperation(operationMath);
//                       startAbility(mathGameIntent);

                   });
               }
           });

        });


    }
    //界面：我的初始化
    private void  initThree(PageSlider pageSlider){
        String userName = DataBaseUtil.getvalue("userName",this);
        String userImg = DataBaseUtil.getvalue("userImgAddress", this);
        Image image = (Image) findComponentById(ResourceTable.Id_user_image);
        Text text =(Text)findComponentById(ResourceTable.Id_user_name_text);

        //渲染头像
//        LoadImageUtil.loadImg(this,);
        System.out.println("---------------------------------数据库图片地址"+userImg);
        LoadImageUtil.loadImg(this, ApiUtil.IMG_BASE_PATH+userImg,image);
        System.out.println("---------------------------------"+ApiUtil.IMG_BASE_PATH+userImg.toString());
        text.setText(userName);

        Text loginout = (Text)findComponentById(ResourceTable.Id_zhuxiao);
        loginout.setClickedListener(component -> {
            System.out.println("=========================================================this:"+this);
            DataBaseUtil.removetoken("token",this);
            DataBaseUtil.removetoken("userName",this);
            DataBaseUtil.removetoken("userFamily",this);
            DataBaseUtil.removetoken("userCall",this);
            DataBaseUtil.removetoken("userImgAddress",this);
            layoutFileIds.clear();
            tabList.removeAllComponents();
            this.present(new LoginAbilitySlice(),new Intent());
        });



    }
    //界面：宝宝社区初始化
    private  void initFour(PageSlider pageSlider){

    }




}
